/**
 * 
 */
package com.waylau.spring.boot.blog.service;

import com.waylau.spring.boot.blog.domain.Authority;
import com.waylau.spring.boot.blog.domain.HotSearch;
import com.waylau.spring.boot.blog.repository.AuthorityRepository;
import com.waylau.spring.boot.blog.repository.HotSearchRepository;
import com.waylau.spring.boot.blog.util.Similarity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Authority 服务.
 * 
 * @since 1.0.0 2017年3月30日
 * @author <a href="https://waylau.com">Way Lau</a>
 */
@Service
public class HotSearchImpl implements HotSearchService {
	
	@Autowired
	private HotSearchRepository hotSearchRepository;

	/**
	 * Venus-热搜算法
	 *
	 * 有问题: 时间衰减曲线的融入
	 *
	 */
	@Override
	public void updateHotSearch(String key) {
		List<HotSearch> hotSearches = hotSearchRepository.findAll();
		HotSearch best = null;
		float bestSimilarity = 0;
		for(HotSearch h: hotSearches){
			float similar = Similarity.getSimilarityRatio(key,h.getName());
			if(similar>0.4&&similar>bestSimilarity){
				bestSimilarity = similar ;
				best = h;
			}
		}
		if(best!=null){
			best.setNum(best.getNum()+1);
			hotSearchRepository.save(best);
		}else{
			best = new HotSearch();
			best.setNum(1L);
			best.setName(key);
		}
		hotSearchRepository.save(best);
	}

	@Override
	public List<HotSearch> getHotSearch() {
		//return hotSearchRepository.findTop6ByOrderByNumAsc();
		return hotSearchRepository.findTop3ByOrderByNumAsc();
	}
}
